package com.itheima;

import com.itheima.pojo.User;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class myUserService implements UserDetailsService {
    public  static Map<String, User> map = new HashMap<>();

    public void initData(){
        com.itheima.pojo.User user1 = new com.itheima.pojo.User();
        user1.setUsername("admin");
        user1.setPassword("$2a$10$oUMCP.4pCIA3s5SpWhAr1Oqsmj.vo88vHCWW07/tlxL8Zl30xWDhy");

        com.itheima.pojo.User user2 = new com.itheima.pojo.User();
        user2.setUsername("lisi");
        user2.setPassword("$2a$10$PZYYkX5ty27tVKEU1PX6uuoLcUeEVHv9w/SnjQ.seHeiUmpl.v6t6");

        map.put(user1.getUsername(),user1);
        map.put(user2.getUsername(),user2);
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       initData();
        User user = map.get(username);
        if (null==user){
            //框架会自动处理
            return null;
        }
        List Authorities =new ArrayList();
        if (username.equals("admin")){
            Authorities.add(new SimpleGrantedAuthority("ROLE_admin"));
        }
        else if (username.equals("lisi")){
            Authorities.add(new SimpleGrantedAuthority("add"));
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),Authorities);
    }
    public static void main(String[] args) {
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode("123");
        System.out.println(encode);


        //$2a$10$oUMCP.4pCIA3s5SpWhAr1Oqsmj.vo88vHCWW07/tlxL8Zl30xWDhy
        //$2a$10$PZYYkX5ty27tVKEU1PX6uuoLcUeEVHv9w/SnjQ.seHeiUmpl.v6t6
        boolean matches = encoder.matches("123", encode);
        System.out.println(matches);


    }
}
